package utils

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var MongoDBClient *mongo.Client
var MongoDB *mongo.Database

// InitMongoDB 初始化MongoDB连接
func InitMongoDB(uri string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		return err
	}

	// 检查连接
	err = client.Ping(ctx, nil)
	if err != nil {
		return err
	}

	MongoDBClient = client
	// 默认使用intelli-dl数据库
	MongoDB = client.Database("intelli-dl")
	log.Println("Connected to MongoDB!")
	return nil
}

// GetMongoCollection 获取MongoDB集合
func GetMongoCollection(dbName, collectionName string) *mongo.Collection {
	return MongoDBClient.Database(dbName).Collection(collectionName)
}

// GetMongoDB 获取默认MongoDB数据库实例
func GetMongoDB() *mongo.Database {
	return MongoDB
}

// CloseMongoDB 关闭MongoDB连接
func CloseMongoDB() {
	if MongoDBClient != nil {
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		_ = MongoDBClient.Disconnect(ctx)
	}
}
